package it.zqdszb.ui.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.flyco.tablayout.SlidingTabLayout;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import it.zqdszb.R;
import it.zqdszb.entity.ChannelTabBean;
import it.zqdszb.library.adapter.pagerAdapter.MyViewPagerAdapter;
import it.zqdszb.library.api.HttpPostService;
import it.zqdszb.library.api.entitys.BaseResult;
import it.zqdszb.library.ui.BaseLazyMVPFragment;
import it.zqdszb.library.utils.utils.RxDataTool;
import it.zqdszb.library.view.EmptyLayout;

/**
 * Created by GH on 2018-05-16.
 */

public class RegionChannelFragment extends BaseLazyMVPFragment {


	@BindView(R.id.tabLayout)
	SlidingTabLayout tabLayout;
	@BindView(R.id.viewpager)
	ViewPager viewpager;
	@BindView(R.id.emptyLayout)
	EmptyLayout emptyLayout;
	private List<ChannelTabBean> childTabData;
	private MyViewPagerAdapter viewPagerAdapter;

	public RegionChannelFragment newInstance(String tabName, int groupId) {
		RegionChannelFragment fragment = new RegionChannelFragment();
		Bundle b = new Bundle();
		b.putSerializable("PagerTitle", tabName);
		b.putInt("groupId", groupId);
		fragment.setArguments(b);
		return fragment;
	}

	@Nullable
	@Override
	public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = setView(inflater, R.layout.fragment_ragion_channel);
		return view;
	}

	@Override
	protected void initView() {
		emptyLayout.showLoading();
		viewPagerAdapter = new MyViewPagerAdapter(getChildFragmentManager());
	}

	@Override
	protected void onFragmentFirstVisible() {
		super.onFragmentFirstVisible();
		Map<String, Object> params = new HashMap<>();
		params.put("groupId", getArguments().getInt("groupId")+"");
		presenter.sendPost(HttpPostService.getTvTab, params, ChannelTabBean.class, true, false, null);
	}

	@Override
	public void onNext(BaseResult result) {
		super.onNext(result);
		childTabData= (List<ChannelTabBean>) result.getResult();
		emptyLayout.showView();
		tabLayout.setVisibility(!RxDataTool.isListEmpty(childTabData)?View.VISIBLE:View.GONE);
		String[] mTitles = new String[childTabData.size()];
		for (ChannelTabBean tabBean : childTabData) {
			String tabName=tabBean.getName();
			int tabPositon=childTabData.indexOf(tabBean);
			mTitles[tabPositon]=tabName;
			viewPagerAdapter.addFragment(new ChannelListFragment().newInstance(tabName,tabBean.getId()), tabName);

		}
		viewpager.setAdapter(viewPagerAdapter);
		tabLayout.setViewPager(viewpager,mTitles);
	}
}
